<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/learning/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/learning/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/learning/css/main.css?v=5.1.1" rel="stylesheet" type="text/css">


  <meta name="keywords" content="Hexo, NexT">








  <link rel="shortcut icon" type="image/x-icon" href="/learning/favicon.ico?v=5.1.1">






<meta name="description" content="W3C菜鸟">
<meta property="og:type" content="website">
<meta property="og:title" content="农家男孩的博客">
<meta property="og:url" content="http://yoursite.com/index.html">
<meta property="og:site_name" content="农家男孩的博客">
<meta property="og:description" content="W3C菜鸟">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="农家男孩的博客">
<meta name="twitter:description" content="W3C菜鸟">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/learning/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/">





  <title>农家男孩的博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left 
   page-home 
 ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/learning/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">农家男孩的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学海无崖</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/learning/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/learning/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/learning/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/learning/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/learning/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2018/03/01/mybatis-cross-database/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2018/03/01/mybatis-cross-database/" itemprop="url">spring整合mybatis实现跨库(实现主从查询)</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-01T10:18:59+08:00">
                2018-03-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="1、简单的实现跨库查询-可以实现主从查询-跨库查询-方法1"><a href="#1、简单的实现跨库查询-可以实现主从查询-跨库查询-方法1" class="headerlink" title="1、简单的实现跨库查询(可以实现主从查询,跨库查询)方法1"></a>1、简单的实现跨库查询(可以实现主从查询,跨库查询)方法1</h3><ol>
<li>配置多个数据源（datasource）</li>
<li>配置多个SqlSessionFactoryBean工场</li>
<li>MapperScannerConfigurer根据不同的mapper目录配置不同的SqlSessionFactory和basePage</li>
<li>注意，同一时间内，只能保证一个数据源的事务(一个方法内包含对两个数据库的操作，你只能保证对一个库有效)</li>
</ol>
<h5 id="实现如下"><a href="#实现如下" class="headerlink" title="实现如下:"></a>实现如下:</h5><h6 id="数据库表"><a href="#数据库表" class="headerlink" title="数据库表"></a>数据库表</h6><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`tb_user`</span> (</span><br><span class="line">  <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">10</span>) <span class="keyword">unsigned</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  <span class="string">`name`</span> <span class="built_in">varchar</span>(<span class="number">50</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  <span class="string">`age`</span> tinyint(<span class="number">3</span>) <span class="keyword">unsigned</span> <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  <span class="string">`gender`</span> <span class="built_in">char</span>(<span class="number">2</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>)</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">1</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8;</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`tb_news`</span> (</span><br><span class="line">  <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">10</span>) <span class="keyword">unsigned</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  <span class="string">`title`</span> <span class="built_in">varchar</span>(<span class="number">50</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  <span class="string">`author`</span> <span class="built_in">varchar</span>(<span class="number">50</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  <span class="string">`content`</span> <span class="built_in">varchar</span>(<span class="number">200</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>)</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">1</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8;</span><br></pre></td></tr></table></figure>
<h6 id="数据库链接配置"><a href="#数据库链接配置" class="headerlink" title="数据库链接配置"></a>数据库链接配置</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">#tb_user</span><br><span class="line">jdbc.username=root</span><br><span class="line">jdbc.password=root</span><br><span class="line">jdbc.driver=com.mysql.jdbc.Driver</span><br><span class="line">jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=true</span><br><span class="line"></span><br><span class="line">#tb_news</span><br><span class="line">news.jdbc.username=root</span><br><span class="line">news.jdbc.password=root</span><br><span class="line">news.jdbc.driver=com.mysql.jdbc.Driver</span><br><span class="line">news.jdbc.url=jdbc:mysql://localhost:3306/caogao?useSSL=true</span><br></pre></td></tr></table></figure>
<h5 id="mybatis-spring文件配置"><a href="#mybatis-spring文件配置" class="headerlink" title="mybatis+spring文件配置"></a>mybatis+spring文件配置</h5><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span> <span class="attr">xmlns:tx</span>=<span class="string">"http://www.springframework.org/schema/tx"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--user库数据源--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userDatasource"</span> <span class="attr">class</span>=<span class="string">"com.zaxxer.hikari.HikariDataSource"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClassName"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.driver&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.username&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.password&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"jdbcUrl"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.url&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--new库数据源--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"newDatasource"</span> <span class="attr">class</span>=<span class="string">"com.zaxxer.hikari.HikariDataSource"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClassName"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.driver&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.username&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.password&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"jdbcUrl"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.url&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--userSqlSessionFactory工场--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userSqlSessionFactory"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.SqlSessionFactoryBean"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"userDatasource"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"mapperLocations"</span> <span class="attr">value</span>=<span class="string">"classpath:cqut/wys/dao/mapper/user/*.xml"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--newSqlSessionFactory工场--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"newSqlSessionFactory"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.SqlSessionFactoryBean"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"newDatasource"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"mapperLocations"</span> <span class="attr">value</span>=<span class="string">"classpath:cqut/wys/dao/mapper/news/*.xml"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--userMapperScannerConfigurer mapper扫描--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userMapperScannerConfigurer"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.mapper.MapperScannerConfigurer"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basePackage"</span> <span class="attr">value</span>=<span class="string">"cqut.wys.dao.mapper.user"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"sqlSessionFactoryBeanName"</span> <span class="attr">value</span>=<span class="string">"userSqlSessionFactory"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--newMapperScannerConfigurer mapper扫描--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"newMapperScannerConfigurer"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.mapper.MapperScannerConfigurer"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basePackage"</span> <span class="attr">value</span>=<span class="string">"cqut.wys.dao.mapper.news"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"sqlSessionFactoryBeanName"</span> <span class="attr">value</span>=<span class="string">"newSqlSessionFactory"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- userDatasource定义事务管理器  --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userTransactionManager"</span> <span class="attr">class</span>=<span class="string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"userDatasource"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- userDatasource事务支持注解  --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">tx:annotation-driven</span> <span class="attr">transaction-manager</span>=<span class="string">"userTransactionManager"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- newDatasource定义事务管理器  --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"newTransactionManager"</span> <span class="attr">class</span>=<span class="string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"newDatasource"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- newDatasource事务支持注解  --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">tx:annotation-driven</span> <span class="attr">transaction-manager</span>=<span class="string">"newTransactionManager"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="此跨库的实现方法是"><a href="#此跨库的实现方法是" class="headerlink" title="此跨库的实现方法是:"></a>此跨库的实现方法是:</h4><ul>
<li>在mapper包的根目录下，不同数据库新建不同的mapper查询包</li>
</ul>
<p><img src="/learning/img/mybatis跨库122.png" alt="image"></p>
<ul>
<li>MapperScannerConfigurer根据不同的mapper查询包配置不同的basepage,sqlSessionFactoryBeanName</li>
</ul>
<ol>
<li>MapperScannerConfigurer配置中cqut.wys.dao.mapper.news mapper查询包就使用newSqlSessionFactory和newDatasource的值</li>
</ol>
<h4 id="此跨库查询方法的优缺点"><a href="#此跨库查询方法的优缺点" class="headerlink" title="此跨库查询方法的优缺点"></a>此跨库查询方法的优缺点</h4><ol>
<li>实现简单</li>
<li>配置繁索，多个数据库就得新建、配置多个sqlSessionFactory和MapperScannerConfigurer。</li>
</ol>
<h4 id="实现源码-方式1"><a href="#实现源码-方式1" class="headerlink" title="实现源码:方式1"></a><a href="https://gitee.com/wuyoushan/learning/tree/master/mybaits-learning/mybatis-cross-database-spring1" target="_blank" rel="noopener">实现源码:方式1</a></h4><h3 id="实现跨库查询-可以实现主从查询-跨库查询-方法2"><a href="#实现跨库查询-可以实现主从查询-跨库查询-方法2" class="headerlink" title="实现跨库查询(可以实现主从查询,跨库查询)方法2"></a>实现跨库查询(可以实现主从查询,跨库查询)方法2</h3><ol>
<li>配置多个数据源（datasource）</li>
<li>使用spring的AbstractRoutingDataSource实现多数据源切换</li>
<li>使用spring的aop，根据不同mapper包配置不同的数据源</li>
<li>注意，同一时间内，只能保证一个数据源的事务(一个方法内包含对两个数据库的操作，你只能保证对一个库有效)</li>
</ol>
<h5 id="实现如下-1"><a href="#实现如下-1" class="headerlink" title="实现如下:"></a>实现如下:</h5><h6 id="数据库链接配置-1"><a href="#数据库链接配置-1" class="headerlink" title="数据库链接配置"></a>数据库链接配置</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">#tb_user</span><br><span class="line">jdbc.username=root</span><br><span class="line">jdbc.password=root</span><br><span class="line">jdbc.driver=com.mysql.jdbc.Driver</span><br><span class="line">jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=true</span><br><span class="line"></span><br><span class="line">#tb_news</span><br><span class="line">news.jdbc.username=root</span><br><span class="line">news.jdbc.password=root</span><br><span class="line">news.jdbc.driver=com.mysql.jdbc.Driver</span><br><span class="line">news.jdbc.url=jdbc:mysql://localhost:3306/caogao?useSSL=true</span><br></pre></td></tr></table></figure>
<h5 id="mybatis-spring文件配置-1"><a href="#mybatis-spring文件配置-1" class="headerlink" title="mybatis+spring文件配置"></a>mybatis+spring文件配置</h5><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="GBK"?&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span> <span class="attr">xmlns:aop</span>=<span class="string">"http://www.springframework.org/schema/aop"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:tx</span>=<span class="string">"http://www.springframework.org/schema/tx"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--user库数据源--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userDatasource"</span> <span class="attr">class</span>=<span class="string">"com.zaxxer.hikari.HikariDataSource"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClassName"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.driver&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.username&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.password&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"jdbcUrl"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.url&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--new库数据源--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"newDatasource"</span> <span class="attr">class</span>=<span class="string">"com.zaxxer.hikari.HikariDataSource"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClassName"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.driver&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.username&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.password&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"jdbcUrl"</span> <span class="attr">value</span>=<span class="string">"$&#123;news.jdbc.url&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--动态数据源datasource--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"datasource"</span> <span class="attr">class</span>=<span class="string">"cqut.wys.utils.DynamicDataSource"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--设置默认数据库源--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"defaultTargetDataSource"</span> <span class="attr">ref</span>=<span class="string">"userDatasource"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"targetDataSources"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">map</span> <span class="attr">key-type</span>=<span class="string">"java.lang.String"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"userDatasource"</span> <span class="attr">value-ref</span>=<span class="string">"userDatasource"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"newDatasource"</span> <span class="attr">value-ref</span>=<span class="string">"newDatasource"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">map</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--数据源切面,选择不同数据源--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"datasourceAspect"</span> <span class="attr">class</span>=<span class="string">"cqut.wys.utils.DataSourceAspect"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">aop:config</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">aop:aspect</span> <span class="attr">ref</span>=<span class="string">"datasourceAspect"</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--数据源选择,news包选择news库--&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--同时可以根据mapper前缀不同实现主从分离(选择不同的主从)--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">aop:pointcut</span> <span class="attr">id</span>=<span class="string">"datasourceSelect"</span> <span class="attr">expression</span>=<span class="string">"execution(* cqut.wys.dao.mapper.news.*.*(..))"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">aop:before</span> <span class="attr">method</span>=<span class="string">"before"</span> <span class="attr">pointcut-ref</span>=<span class="string">"datasourceSelect"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">aop:aspect</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">aop:config</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--sqlSessionFactory工场--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"sqlSessionFactory"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.SqlSessionFactoryBean"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"datasource"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"mapperLocations"</span> <span class="attr">value</span>=<span class="string">"classpath:cqut/wys/dao/mapper/**/*.xml"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--mapperScannerConfigurer mapper扫描--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"mapperScannerConfigurer"</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.mapper.MapperScannerConfigurer"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basePackage"</span> <span class="attr">value</span>=<span class="string">"cqut.wys.dao.mapper"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"sqlSessionFactoryBeanName"</span> <span class="attr">value</span>=<span class="string">"sqlSessionFactory"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--定义事务管理器--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"transactionManager"</span> <span class="attr">class</span>=<span class="string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"datasource"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 事务支持注解  --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">tx:annotation-driven</span> <span class="attr">transaction-manager</span>=<span class="string">"transactionManager"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<h5 id="动态数据源选择实现"><a href="#动态数据源选择实现" class="headerlink" title="动态数据源选择实现"></a>动态数据源选择实现</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DataSourceAspect</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String NEWS = <span class="string">"newDatasource"</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String USER = <span class="string">"userDatasource"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (DataSourceContextHolder.getDbType() == <span class="keyword">null</span>) &#123;</span><br><span class="line">            DataSourceContextHolder.setDbType(NEWS);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DataSourceContextHolder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;String&gt; contextHolder = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setDbType</span><span class="params">(String dbType)</span> </span>&#123;</span><br><span class="line">        contextHolder.set(dbType);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getDbType</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> contextHolder.get();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">clearDbType</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        contextHolder.remove();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicDataSource</span> <span class="keyword">extends</span> <span class="title">AbstractRoutingDataSource</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">determineCurrentLookupKey</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> DataSourceContextHolder.getDbType();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="此跨库查询方法的优缺点-1"><a href="#此跨库查询方法的优缺点-1" class="headerlink" title="此跨库查询方法的优缺点"></a>此跨库查询方法的优缺点</h4><ol>
<li>此实现相对方法1来说较复杂</li>
<li>配置简单，使用比方法1灵活</li>
</ol>
<h4 id="实现源码-方式2"><a href="#实现源码-方式2" class="headerlink" title="实现源码:方式2"></a><a href="https://gitee.com/wuyoushan/learning/tree/master/mybaits-learning/mybatis-cross-database-spring1" target="_blank" rel="noopener">实现源码:方式2</a></h4><h4 id="springboot整合mybatis实现跨库"><a href="#springboot整合mybatis实现跨库" class="headerlink" title="springboot整合mybatis实现跨库"></a>springboot整合mybatis实现跨库</h4><ul>
<li>springboot整合mybatis实现跨库,实现原理和上面一致。在此不再赘述。</li>
<li>源码地址<a href="https://gitee.com/wuyoushan/learning/tree/master/mybaits-learning/mybatis-cross-database-springboot1" target="_blank" rel="noopener">springboot实现方式1</a></li>
<li>源码地址<a href="https://gitee.com/wuyoushan/learning/tree/master/mybaits-learning/mybatis-cross-database-springboot2" target="_blank" rel="noopener">springboot实现方式2</a></li>
</ul>
<h4 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h4><p><a href="http://blog.csdn.net/millery22/article/details/49465425" target="_blank" rel="noopener">http://blog.csdn.net/millery22/article/details/49465425</a></p>
<p><a href="http://blog.csdn.net/neosmith/article/details/61202084" target="_blank" rel="noopener">http://blog.csdn.net/neosmith/article/details/61202084</a></p>
<p><a href="https://www.jianshu.com/p/a042ff2ee2ae" target="_blank" rel="noopener">https://www.jianshu.com/p/a042ff2ee2ae</a></p>
<p><a href="http://blog.csdn.net/ggjlvzjy/article/details/51544016" target="_blank" rel="noopener">http://blog.csdn.net/ggjlvzjy/article/details/51544016</a></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/11/05/threadFactory-create/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/11/05/threadFactory-create/" itemprop="url">threadFactory的创建</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-05T10:11:28+08:00">
                2017-11-05
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>java创建线程有两种方式</p>
<ol>
<li><p>使用Executors去创建</p>
</li>
<li><p>使用ThreadPoolExecutor的方式去创建</p>
</li>
</ol>
<h3 id="阿里巴巴Java开发文档"><a href="#阿里巴巴Java开发文档" class="headerlink" title="阿里巴巴Java开发文档"></a>阿里巴巴Java开发文档</h3><h4 id="六-并发处理中"><a href="#六-并发处理中" class="headerlink" title="(六)并发处理中"></a>(六)并发处理中</h4><p>线程池不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。</p>
<h4 id="Executors返回的线程池对象的弊端如下"><a href="#Executors返回的线程池对象的弊端如下" class="headerlink" title="Executors返回的线程池对象的弊端如下"></a>Executors返回的线程池对象的弊端如下</h4><ul>
<li><p>FixedThreadPool和SingleThreadPool:<br>允许的请求队列长为Integer.MAX_VALUE，可能会堆积大量的请求，从而导致OOM</p>
</li>
<li><p>CachedThreadPool和ScheduledThreadPool:<br>允许的创建线程数量为Integer.MAX_VALUE，可能会创建大量的线程，从而导致OOM</p>
</li>
</ul>
<h3 id="那我们该如何用ThreadPoolExecutor创建线程池呢？"><a href="#那我们该如何用ThreadPoolExecutor创建线程池呢？" class="headerlink" title="那我们该如何用ThreadPoolExecutor创建线程池呢？"></a>那我们该如何用ThreadPoolExecutor创建线程池呢？</h3><h4 id="在此我完全参考了dubbo中创建线程池的方法，代码如下。"><a href="#在此我完全参考了dubbo中创建线程池的方法，代码如下。" class="headerlink" title="在此我完全参考了dubbo中创建线程池的方法，代码如下。"></a>在此我完全参考了dubbo中创建线程池的方法，代码如下。</h4><h4 id="ThreadPool-java代码"><a href="#ThreadPool-java代码" class="headerlink" title="ThreadPool.java代码"></a>ThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ThreadPool</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ThreadPool</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function">Executor <span class="title">getExecutor</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="NamedThreadFactory-java代码"><a href="#NamedThreadFactory-java代码" class="headerlink" title="NamedThreadFactory.java代码"></a>NamedThreadFactory.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * InternalThreadFactory</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/11/1.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NamedThreadFactory</span> <span class="keyword">implements</span> <span class="title">ThreadFactory</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> AtomicInteger POOL_SEQ = <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AtomicInteger mThreadNum = <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String mPrefix;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span> mDaemo;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ThreadGroup mGroup;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NamedThreadFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(<span class="string">"pool-"</span> + POOL_SEQ.getAndIncrement(), <span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NamedThreadFactory</span><span class="params">(String prefix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(prefix, <span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NamedThreadFactory</span><span class="params">(String prefix, <span class="keyword">boolean</span> daemo)</span> </span>&#123;</span><br><span class="line">        mPrefix = prefix + <span class="string">"-thread-"</span>;</span><br><span class="line">        mDaemo = daemo;</span><br><span class="line">        SecurityManager s = System.getSecurityManager();</span><br><span class="line">        mGroup = (s == <span class="keyword">null</span>) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Thread <span class="title">newThread</span><span class="params">(Runnable runnable)</span> </span>&#123;</span><br><span class="line">        String name = mPrefix + mThreadNum.getAndIncrement();</span><br><span class="line">        Thread ret = <span class="keyword">new</span> Thread(mGroup, runnable, name, <span class="number">0</span>);</span><br><span class="line">        ret.setDaemon(mDaemo);</span><br><span class="line">        <span class="keyword">return</span> ret;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ThreadGroup <span class="title">getThreadGroup</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mGroup;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="CachedThreadPool-java代码"><a href="#CachedThreadPool-java代码" class="headerlink" title="CachedThreadPool.java代码"></a>CachedThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此线程池可伸缩，线程空闲一分钟后回收，新请求重新创建线程，来源于：&lt;code&gt;Executors.newCachedThreadPool()&lt;/code&gt;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CachedThreadPool</span> <span class="keyword">implements</span> <span class="title">ThreadPool</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String name = <span class="string">"Dubbo"</span>;</span><br><span class="line">        <span class="keyword">int</span> cores = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> threads = Integer.MAX_VALUE;</span><br><span class="line">        <span class="keyword">int</span> queues = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> alive = <span class="number">60</span> * <span class="number">1000</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues == <span class="number">0</span> ? <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; <span class="number">0</span> ? <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                <span class="keyword">new</span> NamedThreadFactory(name, <span class="keyword">true</span>), <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="FixedThreadPool-java代码"><a href="#FixedThreadPool-java代码" class="headerlink" title="FixedThreadPool.java代码"></a>FixedThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此线程池启动时即创建固定大小的线程数，不做任何伸缩，来源于：&lt;code&gt;Executors.newFixedThreadPool()&lt;/code&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FixedThreadPool</span> <span class="keyword">implements</span> <span class="title">ThreadPool</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String name = <span class="string">"Dubbo"</span>;</span><br><span class="line">        <span class="keyword">int</span> threads = <span class="number">200</span>;</span><br><span class="line">        <span class="keyword">int</span> queues = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(threads,threads,<span class="number">0</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues == <span class="number">0</span> ? <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; <span class="number">0</span> ? <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                <span class="keyword">new</span> NamedThreadFactory(name, <span class="keyword">true</span>), <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="LimitedThreadPool-java代码"><a href="#LimitedThreadPool-java代码" class="headerlink" title="LimitedThreadPool.java代码"></a>LimitedThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此线程池一直增长，直到上限，增长后不收缩。</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LimitedThreadPool</span> <span class="keyword">implements</span> <span class="title">ThreadPool</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String name = <span class="string">"Dubbo"</span>;</span><br><span class="line">        <span class="keyword">int</span> cores = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> threads = <span class="number">200</span>;</span><br><span class="line">        <span class="keyword">int</span> queues = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(cores,threads,Long.MAX_VALUE, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues == <span class="number">0</span> ? <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; <span class="number">0</span> ? <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                <span class="keyword">new</span> NamedThreadFactory(name, <span class="keyword">true</span>), <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意:"></a>注意:</h3><p>上面的线程池的创建和JDK中Executors基于Executors和ThreadPoolExecutor是有所差异的。</p>
<ol>
<li><p>dubbo中线程池创建的线程为守护进程，而使用Executors和ThreadPoolExecutor默认线程工厂创建的线程池为非守护线程。</p>
</li>
<li><p>dubbo中根据参数使用的阻塞队列，以及定义队列的长度都是不一样的。</p>
</li>
</ol>
<h4 id="上面代码完全参考自dubbo项目源码"><a href="#上面代码完全参考自dubbo项目源码" class="headerlink" title="上面代码完全参考自dubbo项目源码"></a>上面代码完全参考自dubbo项目源码</h4><p>git地址 <a href="https://github.com/alibaba/dubbo" target="_blank" rel="noopener">https://github.com/alibaba/dubbo</a></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/10/24/thread-future-callable/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/10/24/thread-future-callable/" itemprop="url">java多线程 Callable和Future的使用</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-24T22:26:00+08:00">
                2017-10-24
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/读书笔记/" itemprop="url" rel="index">
                    <span itemprop="name">读书笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h2 id="Callable和Future的定义"><a href="#Callable和Future的定义" class="headerlink" title="Callable和Future的定义"></a>Callable和Future的定义</h2><h3 id="Callable"><a href="#Callable" class="headerlink" title="Callable"></a>Callable</h3><p>Callable 接口类似于 Runnable，两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果，并且无法抛出经过检查的异常。 </p>
<h3 id="Future"><a href="#Future" class="headerlink" title="Future"></a>Future</h3><p>Future 表示异步计算的结果。它提供了检查计算是否完成的方法，以等待计算的完成，并获取计算的结果。计算完成后只能使用 get 方法来获取结果，如有必要，计算完成前可以阻塞此方法。取消则由 cancel 方法来执行。还提供了其他方法，以确定任务是正常完成还是被取消了。一旦计算完成，就不能再取消计算。如果为了可取消性而使用 Future 但又不提供可用的结果，则可以声明 Future&lt;?&gt; 形式类型、并返回 null 作为底层任务的结果。 </p>
<h3 id="FutureTask"><a href="#FutureTask" class="headerlink" title="FutureTask"></a>FutureTask</h3><p>此类提供了对 Future 的基本实现。仅在计算完成时才能获取结果；如果计算尚未完成，则阻塞 get 方法。一旦计算完成，就不能再重新开始或取消计算。 </p>
<p>可使用 FutureTask 包装 Callable 或 Runnable 对象。因为 FutureTask 实现了 Runnable，所以可将 FutureTask 提交给 Executor 执行。</p>
<h3 id="使用Callable和Future-FutureTask实现的一些例子"><a href="#使用Callable和Future-FutureTask实现的一些例子" class="headerlink" title="使用Callable和Future,FutureTask实现的一些例子"></a>使用Callable和Future,FutureTask实现的一些例子</h3><h4 id="例子1-Future和Callable的简单使用"><a href="#例子1-Future和Callable的简单使用" class="headerlink" title="例子1: Future和Callable的简单使用"></a>例子1: Future和Callable的简单使用</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/24.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CallableImpl</span> <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">Integer</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        <span class="keyword">int</span> i=ThreadLocalRandom.current().nextInt(<span class="number">100</span>);</span><br><span class="line">        System.out.println(<span class="string">"CallableImpl返回值为:"</span>+i);</span><br><span class="line"><span class="comment">//        throw new IllegalArgumentException();</span></span><br><span class="line">        <span class="keyword">return</span> i;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/24.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> ExecutionException, InterruptedException </span>&#123;</span><br><span class="line">        ExecutorService threadPool = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">4</span>, <span class="number">16</span>, <span class="number">20L</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(<span class="number">1024</span>));</span><br><span class="line"></span><br><span class="line">        Callable callable = <span class="keyword">new</span> CallableImpl();</span><br><span class="line">        Future&lt;Integer&gt; future = threadPool.submit(callable);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"haha"</span>);</span><br><span class="line">        System.out.println(<span class="string">"futurn="</span>+future.get());</span><br><span class="line"></span><br><span class="line">        Future&lt;Integer&gt; future1 = threadPool.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="number">123</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        System.out.println(<span class="string">"haha"</span>);</span><br><span class="line">        System.out.println(<span class="string">"future1="</span>+future1.get());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="运行结果为"><a href="#运行结果为" class="headerlink" title="运行结果为:"></a>运行结果为:</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">haha</span><br><span class="line">CallableImpl返回值为:<span class="number">82</span></span><br><span class="line">futurn=<span class="number">82</span></span><br><span class="line">haha</span><br><span class="line">future1=<span class="number">12312</span></span><br></pre></td></tr></table></figure>
<p>从上面获取到的异步执行的结果，future.get()方法将会阻塞顺序执行的过程(同理抛出异常的时候，同样会阻塞顺序进程),<strong>但当没有使用future.get()方法时则不会阻塞</strong>。</p>
<h4 id="例子2-FutureTask的简单使用"><a href="#例子2-FutureTask的简单使用" class="headerlink" title="例子2: FutureTask的简单使用"></a>例子2: FutureTask的简单使用</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/24.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> ExecutionException, InterruptedException </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> startTime=System.currentTimeMillis();</span><br><span class="line">        ExecutorService threadPool = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">4</span>, <span class="number">16</span>, <span class="number">20L</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(<span class="number">1024</span>));</span><br><span class="line"></span><br><span class="line">        FutureTask&lt;Integer&gt; futureTask=<span class="keyword">new</span> FutureTask&lt;&gt;(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="number">123</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        FutureTask&lt;Integer&gt; futureTask1=<span class="keyword">new</span> FutureTask&lt;&gt;(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="number">321</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        threadPool.execute(futureTask);</span><br><span class="line">        <span class="keyword">new</span> Thread(futureTask1).start();</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">long</span> endTime=System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">"花费时间为="</span>+(endTime-startTime));</span><br><span class="line">        </span><br><span class="line">        System.out.println(<span class="string">"futureTask="</span>+futureTask.get());</span><br><span class="line">        System.out.println(<span class="string">"futureTask1="</span>+futureTask1.get());</span><br><span class="line">        System.out.println(<span class="string">"haha"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> endTime1=System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">"花费时间为="</span>+(endTime1-startTime));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="运行结果为-1"><a href="#运行结果为-1" class="headerlink" title="运行结果为:"></a>运行结果为:</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">花费时间为=<span class="number">5</span></span><br><span class="line">futureTask=<span class="number">123</span></span><br><span class="line">futureTask1=<span class="number">321</span></span><br><span class="line">haha</span><br><span class="line">花费时间为=<span class="number">2005</span></span><br></pre></td></tr></table></figure>
<p>FutureTask创建的异步线程，线程池执行的方式不一样的，同时FutureTask还可以使用Thread()执行获取异步结果。其他的使用和Future基本相同</p>
<h4 id="例子3-异步批量获取结果集"><a href="#例子3-异步批量获取结果集" class="headerlink" title="例子3: 异步批量获取结果集"></a>例子3: 异步批量获取结果集</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ForFutureExec</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> ExecutorService pool = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">4</span>, <span class="number">16</span>, <span class="number">20L</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(<span class="number">1024</span>));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> ExecutionException, InterruptedException </span>&#123;</span><br><span class="line">        Long start=System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        List&lt;Future&gt; list=listFuture(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (Future future:list)&#123;</span><br><span class="line">            System.out.println(future.get());</span><br><span class="line">        &#125;</span><br><span class="line">        Long end=System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">"消耗时间="</span>+(end-start));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> List&lt;Future&gt; <span class="title">listFuture</span><span class="params">(Integer id)</span></span>&#123;</span><br><span class="line">        Future&lt;Integer&gt; future1=pool.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> countNum1(id);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        Future&lt;Integer&gt; future2=pool.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> countNum2(id);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        Future&lt;Integer&gt; future3=pool.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> countNum3(id);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        List&lt;Future&gt; list=<span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        list.add(future1);</span><br><span class="line">        list.add(future3);</span><br><span class="line">        list.add(future2);</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">countNum1</span><span class="params">(Integer id)</span></span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.currentThread().getId();</span><br><span class="line">        <span class="keyword">int</span> num=<span class="keyword">new</span> Random().nextInt(<span class="number">10</span>);</span><br><span class="line">        String str=String.format(<span class="string">"返回输出的结果=%d,当前线程=%d,休眠时间=%d"</span>,num,Thread.currentThread().getId(),<span class="number">1000</span>);</span><br><span class="line">        System.out.println(str);</span><br><span class="line">        <span class="keyword">return</span> num;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">countNum2</span><span class="params">(Integer id)</span></span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.currentThread().getId();</span><br><span class="line">        <span class="keyword">int</span> num=<span class="keyword">new</span> Random().nextInt(<span class="number">50</span>);</span><br><span class="line">        String str=String.format(<span class="string">"返回输出的结果=%d,当前线程=%d,休眠时间=%d"</span>,num,Thread.currentThread().getId(),<span class="number">2000</span>);</span><br><span class="line">        System.out.println(str);</span><br><span class="line">        <span class="keyword">return</span> num;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">countNum3</span><span class="params">(Integer id)</span></span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">6000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.currentThread().getId();</span><br><span class="line">        <span class="keyword">int</span> num=<span class="keyword">new</span> Random().nextInt(<span class="number">100</span>);</span><br><span class="line">        String str=String.format(<span class="string">"返回输出的结果=%d,当前线程=%d,休眠时间=%d"</span>,num,Thread.currentThread().getId(),<span class="number">6000</span>);</span><br><span class="line">        System.out.println(str);</span><br><span class="line">        <span class="keyword">return</span> num;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果:"></a>运行结果:</h5><p>由于list中添加顺序的不同导致输出的也不一样<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//由于list添加future的顺序不一样会导致输出的结果有所差异</span></span><br><span class="line">list.add(future1);      <span class="comment">//休眠1000</span></span><br><span class="line">list.add(future3);      <span class="comment">//休眠6000</span></span><br><span class="line">list.add(future2);      <span class="comment">//休眠2000</span></span><br></pre></td></tr></table></figure></p>
<p>输出结果<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">返回输出的结果=<span class="number">7</span>,当前线程=<span class="number">9</span>,休眠时间=<span class="number">1000</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line">返回输出的结果=<span class="number">34</span>,当前线程=<span class="number">10</span>,休眠时间=<span class="number">2000</span></span><br><span class="line">返回输出的结果=<span class="number">81</span>,当前线程=<span class="number">11</span>,休眠时间=<span class="number">6000</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">34</span></span><br><span class="line">消耗时间=<span class="number">6005</span></span><br></pre></td></tr></table></figure></p>
<p>当list的顺序改变时输出的结果也会改变<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">list.add(future1);      <span class="comment">//休眠1000</span></span><br><span class="line">list.add(future2);      <span class="comment">//休眠2000</span></span><br><span class="line">list.add(future3);      <span class="comment">//休眠6000</span></span><br></pre></td></tr></table></figure></p>
<p>输出结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">返回输出的结果=<span class="number">9</span>,当前线程=<span class="number">9</span>,休眠时间=<span class="number">1000</span></span><br><span class="line"><span class="number">9</span></span><br><span class="line">返回输出的结果=<span class="number">3</span>,当前线程=<span class="number">10</span>,休眠时间=<span class="number">2000</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line">返回输出的结果=<span class="number">14</span>,当前线程=<span class="number">11</span>,休眠时间=<span class="number">6000</span></span><br><span class="line"><span class="number">14</span></span><br><span class="line">消耗时间=<span class="number">6004</span></span><br></pre></td></tr></table></figure></p>
<h4 id="例子4-异步批量获取结果集4"><a href="#例子4-异步批量获取结果集4" class="headerlink" title="例子4: 异步批量获取结果集4"></a>例子4: 异步批量获取结果集4</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/19.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> ExecutorService pool = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">4</span>, <span class="number">16</span>, <span class="number">20L</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(<span class="number">1024</span>));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> ExecutionException, InterruptedException </span>&#123;</span><br><span class="line">        Long start=System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        List&lt;Future&gt; list=<span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">8</span>);</span><br><span class="line">        <span class="comment">//异步执行</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;<span class="number">4</span>;i++)&#123;</span><br><span class="line">            list.add(asynExec(i*<span class="number">1000</span>));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//异步执行</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j=<span class="number">4</span>;j&gt;<span class="number">1</span>;j--)&#123;</span><br><span class="line">            list.add(asynExec(j*<span class="number">1000</span>));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (Future future:list)&#123;</span><br><span class="line">            System.out.println(future.get());</span><br><span class="line">        &#125;</span><br><span class="line">        Long end=System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">"异步执行消耗时间="</span>+(end-start));</span><br><span class="line"></span><br><span class="line">        Long start1=System.currentTimeMillis();</span><br><span class="line">        List&lt;Integer&gt; list1=<span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">4</span>);</span><br><span class="line">        <span class="comment">//同步执行</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;<span class="number">4</span>;i++)&#123;</span><br><span class="line">            list1.add(synchronizedExec(i*<span class="number">1000</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//同步执行</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j=<span class="number">4</span>;j&gt;<span class="number">1</span>;j--)&#123;</span><br><span class="line">            list1.add(synchronizedExec(j*<span class="number">1000</span>));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> result:list1)&#123;</span><br><span class="line">            System.out.println(result);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Long end1=System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">"同步执行消耗时间="</span>+(end1-start1));</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Future&lt;Integer&gt; <span class="title">asynExec</span><span class="params">(<span class="keyword">int</span> time)</span></span>&#123;</span><br><span class="line">        Future&lt;Integer&gt; future=pool.submit(<span class="keyword">new</span> Callable&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> countNum(time);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">return</span> future;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">synchronizedExec</span><span class="params">(<span class="keyword">int</span> time)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> countNum(time);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">countNum</span><span class="params">(<span class="keyword">int</span> time)</span></span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(time);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.currentThread().getId();</span><br><span class="line">        <span class="keyword">int</span> num=<span class="keyword">new</span> Random().nextInt(<span class="number">10</span>);</span><br><span class="line">        String str=String.format(<span class="string">"返回输出的结果=%d,当前线程=%d,休眠时间=%d"</span>,num,Thread.currentThread().getId(),time);</span><br><span class="line">        System.out.println(str);</span><br><span class="line">        <span class="keyword">return</span> num;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="运行结果为-2"><a href="#运行结果为-2" class="headerlink" title="运行结果为:"></a>运行结果为:</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">返回输出的结果=<span class="number">8</span>,当前线程=<span class="number">9</span>,休眠时间=<span class="number">1000</span></span><br><span class="line"><span class="number">8</span></span><br><span class="line">返回输出的结果=<span class="number">2</span>,当前线程=<span class="number">10</span>,休眠时间=<span class="number">2000</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line">返回输出的结果=<span class="number">7</span>,当前线程=<span class="number">11</span>,休眠时间=<span class="number">3000</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line">返回输出的结果=<span class="number">1</span>,当前线程=<span class="number">12</span>,休眠时间=<span class="number">4000</span></span><br><span class="line"><span class="number">1</span></span><br><span class="line">返回输出的结果=<span class="number">2</span>,当前线程=<span class="number">10</span>,休眠时间=<span class="number">2000</span></span><br><span class="line">返回输出的结果=<span class="number">1</span>,当前线程=<span class="number">9</span>,休眠时间=<span class="number">3000</span></span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line">异步执行消耗时间=<span class="number">4033</span></span><br><span class="line">返回输出的结果=<span class="number">4</span>,当前线程=<span class="number">1</span>,休眠时间=<span class="number">1000</span></span><br><span class="line">返回输出的结果=<span class="number">8</span>,当前线程=<span class="number">1</span>,休眠时间=<span class="number">2000</span></span><br><span class="line">返回输出的结果=<span class="number">0</span>,当前线程=<span class="number">1</span>,休眠时间=<span class="number">3000</span></span><br><span class="line">返回输出的结果=<span class="number">3</span>,当前线程=<span class="number">1</span>,休眠时间=<span class="number">4000</span></span><br><span class="line">返回输出的结果=<span class="number">9</span>,当前线程=<span class="number">1</span>,休眠时间=<span class="number">3000</span></span><br><span class="line">返回输出的结果=<span class="number">4</span>,当前线程=<span class="number">1</span>,休眠时间=<span class="number">2000</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">8</span></span><br><span class="line"><span class="number">0</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="number">9</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line">同步执行消耗时间=<span class="number">15001</span></span><br></pre></td></tr></table></figure>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/08/09/springboot-builder-docker/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/08/09/springboot-builder-docker/" itemprop="url">springboot构建镜像</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-09T11:43:45+08:00">
                2017-08-09
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/docker/" itemprop="url" rel="index">
                    <span itemprop="name">docker</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="基于现成的java镜像，构建发布一个springboot应用的镜像"><a href="#基于现成的java镜像，构建发布一个springboot应用的镜像" class="headerlink" title="基于现成的java镜像，构建发布一个springboot应用的镜像"></a>基于现成的java镜像，构建发布一个springboot应用的镜像</h3><p><a href="https://gitee.com/wuyoushan/learning/tree/master/springboot-demo" target="_blank" rel="noopener">一个简单的springboot地址</a></p>
<h4 id="系统环境"><a href="#系统环境" class="headerlink" title="系统环境"></a>系统环境</h4><ul>
<li>java 8</li>
<li>Centos7.3</li>
<li>docker 1.12.6</li>
</ul>
<p><strong>由于springboot应用中内置了应用服务器(默认为tomcat)，根据个人喜好可以修改为jetty或者undertow等应用服务器。springboot程序的运行只依赖于jdk</strong></p>
<ol>
<li>基于现成的java进行构建springboot镜像</li>
<li>首先从国内的docker镜像中pull拉取docker镜像(默认会从<a href="https://hub.docker.com" target="_blank" rel="noopener">https://hub.docker.com</a> 中拉取镜像)。由于国内的网络状态从官网镜像仓库拉会很不稳定。推荐使用国内进行。在这里我使用的是daocloud国内镜像<br><img src="/learning/img/springboot-search-java.png" alt="image"></li>
</ol>
<p>查找到的镜像</p>
<p><img src="/learning/img/springboot-docker-java-2.png" alt="image"></p>
<p>单击进去查看镜像信息</p>
<p><img src="/learning/img/springboot-docker-java-3.png" alt="image"></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker pull daocloud.io/library/java:openjdk-8u40</span><br></pre></td></tr></table></figure>
<p>也可以将链接改成<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker pull daocloud.io/library/java:latest</span><br></pre></td></tr></table></figure></p>
<p>表示拉取最新的镜像</p>
<p>拉取完,运行docker images命令查看，镜像已经拉到本地<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost <span class="built_in">log</span>]<span class="comment"># docker images;</span></span><br><span class="line">REPOSITORY                     TAG                 IMAGE ID            CREATED             SIZE</span><br><span class="line">hub.c.163.com/library/tomcat   latest              a2fbbcebd67e        4 weeks ago         333.9 MB</span><br><span class="line">hub.c.163.com/library/jetty    latest              2d50930b2488        12 weeks ago        319.9 MB</span><br><span class="line">daocloud.io/library/java       openjdk-8u40        4aefdb29fd43        2 years ago         815.5 MB</span><br></pre></td></tr></table></figure></p>
<p>创建Dockerfile文件,文件内容如下<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">FROM daocloud.io/library/java:latest</span><br><span class="line">MAINTAINER yourname XXX@qq.com</span><br><span class="line">VOLUME /tmp</span><br><span class="line">ADD ./springboot-demo-1.0-SNAPSHOT.jar app.jar</span><br><span class="line">ENV JAVA_OPTS=&quot;&quot;</span><br><span class="line">ENTRYPOINT [ &quot;sh&quot;, &quot;-c&quot;, &quot;java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar&quot; ]</span><br></pre></td></tr></table></figure></p>
<p>运行docker build构建镜像(注意最后那个点表示的是当前路径)<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker build -t springboot-web:latest .</span><br></pre></td></tr></table></figure></p>
<p>运行过程:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost docker]# docker build -t springboot-web:latest .</span><br><span class="line">Sending build context to Docker daemon 23.89 MB</span><br><span class="line">Step 1 : FROM daocloud.io/library/java</span><br><span class="line"> ---&gt; d23bdf5b1b1b</span><br><span class="line">Step 2 : MAINTAINER yourname XXX@qq.com</span><br><span class="line"> ---&gt; Running in e964c60f0905</span><br><span class="line"> ---&gt; 7c63ec5f8f5f</span><br><span class="line">Removing intermediate container e964c60f0905</span><br><span class="line">Step 3 : VOLUME /tmp</span><br><span class="line"> ---&gt; Running in abe539105b82</span><br><span class="line"> ---&gt; 738eeef06071</span><br><span class="line">Removing intermediate container abe539105b82</span><br><span class="line">Step 4 : ADD ./springboot-demo-1.0-SNAPSHOT.jar app.jar</span><br><span class="line"> ---&gt; dccf66b86b9f</span><br><span class="line">Removing intermediate container 974b60d0e248</span><br><span class="line">Step 5 : ENV JAVA_OPTS &quot;&quot;</span><br><span class="line"> ---&gt; Running in 7eeea5fda6a7</span><br><span class="line"> ---&gt; 591db4ec14b6</span><br><span class="line">Removing intermediate container 7eeea5fda6a7</span><br><span class="line">Step 6 : ENTRYPOINT sh -c java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar</span><br><span class="line"> ---&gt; Running in 9456005ad15e</span><br><span class="line"> ---&gt; eea988cca381</span><br><span class="line">Removing intermediate container 9456005ad15e</span><br><span class="line">Successfully built eea988cca381</span><br><span class="line">[root@localhost docker]#</span><br></pre></td></tr></table></figure></p>
<p>构建成功查看构建成功的镜像<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost docker]# docker images</span><br><span class="line">REPOSITORY                     TAG                 IMAGE ID            CREATED             SIZE</span><br><span class="line">springboot-web                 latest              dbaafca494ed        11 days ago         667 MB</span><br><span class="line">hub.c.163.com/library/tomcat   latest              a2fbbcebd67e        6 weeks ago         333.9 MB</span><br><span class="line">hub.c.163.com/library/jetty    latest              2d50930b2488        3 months ago        319.9 MB</span><br><span class="line">daocloud.io/library/java       latest              d23bdf5b1b1b        6 months ago        643.1 MB</span><br></pre></td></tr></table></figure></p>
<p>发现有一个springboot-web镜像名，表示我们构建的镜像已经在本地仓库中。</p>
<p>运行构造的springboot-web镜像<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker run -it -d -p 8080:8080 springboot-web</span><br></pre></td></tr></table></figure></p>
<p>访问地址: <a href="http://localhost:8080/user/list" target="_blank" rel="noopener">http://localhost:8080/user/list</a> 运行结果为:</p>
<p><img src="/learning/img/springboot-demo.png" alt="image"></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/08/08/thread-summary/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/08/08/thread-summary/" itemprop="url">线程总结</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-08T18:26:47+08:00">
                2017-08-08
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h2 id="线程创建的两种方式"><a href="#线程创建的两种方式" class="headerlink" title="线程创建的两种方式:"></a>线程创建的两种方式:</h2><ol>
<li>继承Thread类:</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyThread</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//// TODO</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">MyThread mt=<span class="keyword">new</span> MyThread();</span><br><span class="line">mt.start();</span><br></pre></td></tr></table></figure>
<ol>
<li>实现Runnable接口:<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyThread</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//// TODO</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">MyThread mt=<span class="keyword">new</span> MyThread();</span><br><span class="line">mt.start();</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="线程创建的两种方式比较"><a href="#线程创建的两种方式比较" class="headerlink" title="线程创建的两种方式比较"></a>线程创建的两种方式比较</h2><ol>
<li><p>Runnable方式可以避免Thread方式由于java单继承特性带来的缺陷</p>
</li>
<li><p>Runnable的代码可以被多个线程(Thread实例)共享,适合于多个线程处理同一资源的情况</p>
</li>
</ol>
<h2 id="Thread模拟买票"><a href="#Thread模拟买票" class="headerlink" title="Thread模拟买票"></a>Thread模拟买票</h2><h3 id="1-继承Thread类"><a href="#1-继承Thread类" class="headerlink" title="1. 继承Thread类"></a>1. 继承Thread类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义一个线程类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyThread</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> ticketsCount = <span class="number">5</span>;  <span class="comment">//一共有5张火车票</span></span><br><span class="line">	<span class="keyword">private</span> String name;   <span class="comment">//窗口，就是线程的名字</span></span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">MyThread</span><span class="params">(String name)</span></span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.name = name;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//创建启动线程的方法</span></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">while</span>(ticketsCount &gt; <span class="number">0</span>)&#123;</span><br><span class="line">			ticketsCount--;  <span class="comment">//如果还有票，就卖掉一张</span></span><br><span class="line">			System.out.println(name +<span class="string">"卖了1张票，剩余票数为"</span>+ticketsCount);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TicketsThread</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		<span class="comment">//创建3个线程，模拟三个窗口卖票</span></span><br><span class="line">		MyThread mt1 = <span class="keyword">new</span> MyThread(<span class="string">"窗口1"</span>);</span><br><span class="line">		MyThread mt2 = <span class="keyword">new</span> MyThread(<span class="string">"窗口2"</span>);</span><br><span class="line">		MyThread mt3 = <span class="keyword">new</span> MyThread(<span class="string">"窗口3"</span>);</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//启动这三个线程，就是窗口开始卖票</span></span><br><span class="line">		mt1.start();</span><br><span class="line">		mt2.start();</span><br><span class="line">		mt3.start();</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序的输出结果:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 总共只有5张火车票，每个窗口卖了5次，结果卖出15张票，这是不合理的</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">4</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">3</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">2</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">1</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">0</span></span><br><span class="line">窗口<span class="number">2</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">4</span></span><br><span class="line">窗口<span class="number">2</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">3</span></span><br><span class="line">窗口<span class="number">2</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">2</span></span><br><span class="line">窗口<span class="number">2</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">1</span></span><br><span class="line">窗口<span class="number">2</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">0</span></span><br><span class="line">窗口<span class="number">3</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">4</span></span><br><span class="line">窗口<span class="number">3</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">3</span></span><br><span class="line">窗口<span class="number">3</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">2</span></span><br><span class="line">窗口<span class="number">3</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">1</span></span><br><span class="line">窗口<span class="number">3</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">0</span></span><br></pre></td></tr></table></figure></p>
<h3 id="2-实现Runnable-接口"><a href="#2-实现Runnable-接口" class="headerlink" title="2. 实现Runnable 接口"></a>2. 实现Runnable 接口</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建一个线程类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyThread1</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> ticketsCount = <span class="number">5</span>;  <span class="comment">//一共有5张火车票</span></span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="comment">//如果ticketsCount不为0，说明还有火车票，可以继续卖</span></span><br><span class="line">		<span class="keyword">while</span>(ticketsCount &gt; <span class="number">0</span> )&#123;</span><br><span class="line">			ticketsCount--;</span><br><span class="line">			<span class="comment">//Thread.currentThread().getName()   获得当前线程的名字</span></span><br><span class="line">			System.out.println(Thread.currentThread().getName() +<span class="string">"卖了1张票，剩余票数为"</span>+ticketsCount);</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TicketsThread1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		MyThread1 mt = <span class="keyword">new</span> MyThread1();</span><br><span class="line">		<span class="comment">//创建三个线程,来模拟三个售票窗口</span></span><br><span class="line">		Thread th1 = <span class="keyword">new</span> Thread(mt,<span class="string">"窗口1"</span>);</span><br><span class="line">		Thread th2 = <span class="keyword">new</span> Thread(mt,<span class="string">"窗口2"</span>);</span><br><span class="line">		Thread th3 = <span class="keyword">new</span> Thread(mt,<span class="string">"窗口3"</span>);</span><br><span class="line">		<span class="comment">//启动三个线程，就是三个窗口开始卖票</span></span><br><span class="line">		th1.start();</span><br><span class="line">		th2.start();</span><br><span class="line">		th3.start();</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序的运行结果<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">4</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">3</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">2</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">1</span></span><br><span class="line">窗口<span class="number">1</span>卖了<span class="number">1</span>张票，剩余票数为<span class="number">0</span></span><br></pre></td></tr></table></figure></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/08/08/two-kinds-java-threads/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/08/08/two-kinds-java-threads/" itemprop="url">java线程有两种</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-08T18:26:26+08:00">
                2017-08-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h2 id="java线程有两类"><a href="#java线程有两类" class="headerlink" title="java线程有两类"></a>java线程有两类</h2><h3 id="1-用户线程-运行在前台-执行具体的任务"><a href="#1-用户线程-运行在前台-执行具体的任务" class="headerlink" title="1. 用户线程:运行在前台,执行具体的任务"></a>1. 用户线程:运行在前台,执行具体的任务</h3><h3 id="2-程序的主线程、连接网络的子线程等都是用户线程"><a href="#2-程序的主线程、连接网络的子线程等都是用户线程" class="headerlink" title="2. 程序的主线程、连接网络的子线程等都是用户线程"></a>2. 程序的主线程、连接网络的子线程等都是用户线程</h3><p><strong>守护线程:</strong> 运行在后台,为其他前台线程服务</p>
<ol>
<li><p>特点:</p>
<ul>
<li>一旦所有用户线程都结束运行,守护线程会随JVM一起结束工作</li>
</ul>
</li>
<li><p>应用:</p>
</li>
</ol>
<ul>
<li><p>数据库连接池中监测线程</p>
</li>
<li><p>JVM虚拟机启动后的监测线程</p>
</li>
<li>最常见的守护线程:垃圾回收线程.</li>
</ul>
<p><strong>如何设置守护线程</strong></p>
<p>可以通过调用Thread类的setDaemon(true)方法来设置当前的线程为守护线程</p>
<p>注意事项:</p>
<ol>
<li><p>setDaemon(true)必须在start()方法之前调用,否则会抛出IllegalThreadStateException异常</p>
</li>
<li><p>在守护线程中产生的新线程也是守护线程</p>
</li>
<li>不是所有的任务都可以分配给守护线程来执行,比如读写操作或计算逻辑</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DaemonThread</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"进入守护进程"</span>+Thread.currentThread().getName());</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            writeToFile();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"退出守护进程"</span>+Thread.currentThread().getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">writeToFile</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        File fileName=<span class="keyword">new</span> File(<span class="string">"C:"</span>+File.separator+<span class="string">"daemon.txt"</span>);</span><br><span class="line">        OutputStream os=<span class="keyword">new</span> FileOutputStream(fileName,<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">int</span> count=<span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span> (count&lt;<span class="number">999</span>)&#123;</span><br><span class="line">            os.write((<span class="string">"\r\nword"</span>+count).getBytes());</span><br><span class="line">            System.out.println(<span class="string">"守护进程"</span>+Thread.currentThread().getName()+<span class="string">"向文件中写入了word"</span>+count++);</span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DaemonThreadDemo</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"进入主进程"</span>+Thread.currentThread().getName());</span><br><span class="line">        DaemonThread daemonThread=<span class="keyword">new</span> DaemonThread();</span><br><span class="line">        Thread thread=<span class="keyword">new</span> Thread(daemonThread);</span><br><span class="line">        thread.setDaemon(<span class="keyword">true</span>);</span><br><span class="line">        thread.start();</span><br><span class="line"></span><br><span class="line">        Scanner sc=<span class="keyword">new</span> Scanner(System.in);</span><br><span class="line">        sc.next();</span><br><span class="line">        System.out.println(<span class="string">"退出退出主进程"</span>+Thread.currentThread().getName());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>向程序输入:dd<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">进入主进程main</span><br><span class="line">进入守护进程Thread-<span class="number">0</span></span><br><span class="line">守护进程Thread-<span class="number">0</span>向文件中写入了word0</span><br><span class="line">守护进程Thread-<span class="number">0</span>向文件中写入了word1</span><br><span class="line">守护进程Thread-<span class="number">0</span>向文件中写入了word2</span><br><span class="line">守护进程Thread-<span class="number">0</span>向文件中写入了word3</span><br><span class="line">dd守护进程Thread-<span class="number">0</span>向文件中写入了word4</span><br><span class="line"></span><br><span class="line">退出退出主进程main</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果:</p>
<p><img src="/learning/img/daemon20170730143936.png" alt="images"></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/07/23/timer-schedule-four/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/07/23/timer-schedule-four/" itemprop="url">5.1.5方法scheduleAtFixedRete(TimerTask task,Date firstTime,long period)的测试</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-23T22:46:29+08:00">
                2017-07-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/读书笔记/" itemprop="url" rel="index">
                    <span itemprop="name">读书笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>方法schedule和方法scheduleAtFixedRate都会按顺序执行，所以不要考虑非线程安全的情况。<br>方法schedule和方法scheduleAtFixedRate只在于不延时的情况。</p>
<p>使用schedule方法:如果执行任务的时间没有被延时，那么下一次任务的执行时间参考的是上一次任务的“开始”时的时间来计算。</p>
<p>使用scheduleAtFixedRate方法:如果执行任务的时间没有被延时，那么下一次任务的执行时间参考的是上一次任务的“结束”时的时间来计算。</p>
<p>延时的情况则没有区别，也就是使用schedule或scheduleAtFixedRate方法都是如果执行任务的时间被延时，那么下一次任务的执行时间参考的是上一次任务“结束”时的时间来计算。</p>
<p><strong>1. 测试schedule方法任务不延时</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> runCount=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask1</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span>&#123;</span><br><span class="line">                System.out.println(<span class="string">"1 begin 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">                System.out.println(<span class="string">"1 end 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                runCount++;</span><br><span class="line">                <span class="keyword">if</span> (runCount==<span class="number">5</span>)&#123;</span><br><span class="line">                    timer.cancel();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;<span class="keyword">catch</span>(InterruptedException e)&#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTask1 task = <span class="keyword">new</span> MyTask1();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-05-19 08:44:00"</span>;</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(task,dateRef,<span class="number">3000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">44</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">39</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">39</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">40</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">42</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">43</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">45</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">46</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">48</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">49</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">51</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">12</span>:<span class="number">52</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>控制台大印的结果证明，在不延迟的情况下，如果执行任务的时间没有被延时，则下一次执行任务的时间是上一次任务的开始时间加上delay时间</p>
<p><strong>2. 测试schedule方法任务</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> runCount=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask1</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span>&#123;</span><br><span class="line">                System.out.println(<span class="string">"1 begin 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                Thread.sleep(<span class="number">5000</span>);</span><br><span class="line">                System.out.println(<span class="string">"1   end 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                runCount++;</span><br><span class="line">                <span class="keyword">if</span> (runCount==<span class="number">5</span>)&#123;</span><br><span class="line">                    timer.cancel();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;<span class="keyword">catch</span>(InterruptedException e)&#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTask1 task = <span class="keyword">new</span> MyTask1();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-05-20 08:44:00"</span>;</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(task,dateRef,<span class="number">2000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Sat May <span class="number">20</span> <span class="number">08</span>:<span class="number">44</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">35</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">35</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">40</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">40</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">45</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">45</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">50</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">50</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">55</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">23</span>:<span class="number">55</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">24</span>:<span class="number">00</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>从控制台打印的结果来看，如果执行任务的时间被延迟，那么下一次任务的执行时间以上一次任务“结束”时的时间为参考计算</p>
<p><strong>3. 测试scheduleAtFixedRate方法任务不延时</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> runCount=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask1</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span>&#123;</span><br><span class="line">                System.out.println(<span class="string">"1 begin 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">                System.out.println(<span class="string">"1   end 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                runCount++;</span><br><span class="line">                <span class="keyword">if</span> (runCount==<span class="number">5</span>)&#123;</span><br><span class="line">                    timer.cancel();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;<span class="keyword">catch</span>(InterruptedException e)&#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTask1 task = <span class="keyword">new</span> MyTask1();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-05-20 08:44:00"</span>;</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(task,dateRef,<span class="number">3000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Sat May <span class="number">20</span> <span class="number">08</span>:<span class="number">44</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">46</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">46</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">48</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">49</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">51</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">52</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">54</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">55</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">57</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">25</span>:<span class="number">58</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">26</span>:<span class="number">00</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>控制台打印的结果证明，如果执行任务的时间没有被延迟时，则下一次执行任务的时间是上一次任务的开始时间加上delay时间。</p>
<p><strong>4. 测试scheduleAtFixedRate方法任务延时</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> runCount=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask1</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span>&#123;</span><br><span class="line">                System.out.println(<span class="string">"1 begin 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                Thread.sleep(<span class="number">5000</span>);</span><br><span class="line">                System.out.println(<span class="string">"1   end 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">                runCount++;</span><br><span class="line">                <span class="keyword">if</span> (runCount==<span class="number">5</span>)&#123;</span><br><span class="line">                    timer.cancel();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;<span class="keyword">catch</span>(InterruptedException e)&#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTask1 task = <span class="keyword">new</span> MyTask1();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-05-20 08:44:00"</span>;</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.scheduleAtFixedRate(task,dateRef,<span class="number">2000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Sat May <span class="number">20</span> <span class="number">08</span>:<span class="number">44</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">03</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">03</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">08</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">08</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">13</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">13</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">18</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">18</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">23</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">23</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">46</span>:<span class="number">28</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>从控制台打印的结果来看，如果执行任务的时间被延迟时，那么下一次任务的执行时间以上一次任务“结束”时的时间为参考来计算。</p>
<p><strong>5. 验证schedule方法不具有追赶执行性</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask1</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"1 begin 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">            System.out.println(<span class="string">"1   end 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTask1 task = <span class="keyword">new</span> MyTask1();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-05-20 08:44:00"</span>;</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(task,dateRef,<span class="number">5000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Sat May <span class="number">20</span> <span class="number">08</span>:<span class="number">44</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">29</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">29</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">29</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">34</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">34</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">39</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">39</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">44</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">44</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p><strong>6. 验证scheduleAtFixedRate方法具有追赶执行性</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask1</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"1 begin 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">            System.out.println(<span class="string">"1   end 运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTask1 task = <span class="keyword">new</span> MyTask1();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-05-20 08:44:00"</span>;</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.scheduleAtFixedRate(task,dateRef,<span class="number">2000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span> begin 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line"><span class="number">1</span>   end 运行了！时间为:Mon May <span class="number">22</span> <span class="number">08</span>:<span class="number">52</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>两个时间段内所对应的Task任务被“补充性”执行了，这就是Task任务追赶执行的特性。</p>
<blockquote>
<p>摘选自 java多线程核心编程技术-5.1.5</p>
</blockquote>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/07/23/timer-schedule-three/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/07/23/timer-schedule-three/" itemprop="url">5.1.4方法schedule(TimerTask task,long delay,long period)的测试</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-23T22:45:28+08:00">
                2017-07-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/读书笔记/" itemprop="url" rel="index">
                    <span itemprop="name">读书笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>该方法的作用是以执行schedule(TimerTask task,long delay,long period)方法当前的时间为参考时间，在此时间基础上延迟指定的毫秒数，再以某一间隔时间无限次数地执行某一任务。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"运行了！时间为:"</span> +<span class="keyword">new</span> Date());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Timer timer = <span class="keyword">new</span> Timer();</span><br><span class="line">        MyTask task = <span class="keyword">new</span> MyTask();</span><br><span class="line">        System.out.println(<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">        timer.schedule(task,<span class="number">3000</span>,<span class="number">5000</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序运行后的结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">当前时间:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">16</span>:<span class="number">04</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">16</span>:<span class="number">07</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">16</span>:<span class="number">12</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">16</span>:<span class="number">17</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">16</span>:<span class="number">22</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">16</span>:<span class="number">27</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>凡是使用方法中带有period参数的，都是无限循环执行TimerTask中的任务。</p>
<blockquote>
<p>摘选自 java多线程核心编程技术-5.1.4</p>
</blockquote>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/07/23/timer-schedule-two/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/07/23/timer-schedule-two/" itemprop="url">5.1.3方法schedule(TimerTask task,long delay)的测试</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-23T22:44:18+08:00">
                2017-07-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/读书笔记/" itemprop="url" rel="index">
                    <span itemprop="name">读书笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p><strong>5.1.3方法schedule(TimerTask task,long delay)的测试</strong><br>该方法的作用是以执行schedule(TimerTask task,long delay)方法当前的时间为参考时间，在此时间基础上延迟指定的毫秒数后执行一次TimerTask任务。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"运行了！时间为:"</span> +<span class="keyword">new</span> Date());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Timer timer = <span class="keyword">new</span> Timer();</span><br><span class="line">        MyTask task = <span class="keyword">new</span> MyTask();</span><br><span class="line">        System.out.println(<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">        timer.schedule(task, <span class="number">7000</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>任务task被延迟7秒执行。程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">当前时间:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">07</span>:<span class="number">08</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Fri May <span class="number">19</span> <span class="number">08</span>:<span class="number">07</span>:<span class="number">15</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>摘选自 java多线程核心编程技术-5.1.3</p>
</blockquote>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/07/23/timer-schedule-one/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/learning/2017/07/23/timer-schedule-one/" itemprop="url">5.1.2方法schedule(TimerTask task,Date firstTime,long period)的测试</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-23T22:43:10+08:00">
                2017-07-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/读书笔记/" itemprop="url" rel="index">
                    <span itemprop="name">读书笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>该方法的作用是在指定的期之后，按指定的间隔周期性地无限循环地执行某一任务。</p>
<p><strong>1. 计划任务晚于当前任务:在未来执行的效果</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"运行了！时间为:"</span>+<span class="keyword">new</span> Date());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            MyTask task=<span class="keyword">new</span> MyTask();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-5-15 8:09:00"</span>;</span><br><span class="line">            Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(task,dateRef,<span class="number">4000</span>);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">09</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">22</span>:<span class="number">17</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">22</span>:<span class="number">17</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">22</span>:<span class="number">21</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">22</span>:<span class="number">25</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">22</span>:<span class="number">29</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>从运行的结果来看，每隔4秒运行一次TimerTask任务，并且是无限期地重复执行。</p>
<p><strong>2. 计划任务早于当前时间：提前运行的效果</strong><br>如果计划时间早于当前时间，则立即执行task任务。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            MyTask task=<span class="keyword">new</span> MyTask();</span><br><span class="line">            SimpleDateFormat sdf=<span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString=<span class="string">"2017-5-15 8:09:00"</span>;</span><br><span class="line">            Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line">            Date dateRef=sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span>+dateRef.toString()+<span class="string">"当前时间:"</span>+<span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(task,dateRef,<span class="number">4000</span>);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Mon May <span class="number">15</span> <span class="number">08</span>:<span class="number">09</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">30</span>:<span class="number">33</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">30</span>:<span class="number">33</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">30</span>:<span class="number">37</span> CST <span class="number">2017</span></span><br><span class="line">运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">30</span>:<span class="number">41</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p><strong>3. 任务执行时间被延时</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTaskA</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">"A运行了！时间为:"</span> + <span class="keyword">new</span> Date());</span><br><span class="line">                Thread.sleep(<span class="number">5000</span>);</span><br><span class="line">                System.out.println(<span class="string">"A结束了！时间为:"</span> + <span class="keyword">new</span> Date());</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTaskA taskA = <span class="keyword">new</span> MyTaskA();</span><br><span class="line">            SimpleDateFormat sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString = <span class="string">"2017-5-15 8:09:00"</span>;</span><br><span class="line">            Timer timer = <span class="keyword">new</span> Timer();</span><br><span class="line">            Date dateRef = sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span> + dateRef.toString() + <span class="string">"当前时间:"</span> + <span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(taskA, dateRef, <span class="number">4000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Mon May <span class="number">15</span> <span class="number">08</span>:<span class="number">09</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">18</span> CST <span class="number">2017</span></span><br><span class="line">A运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">18</span> CST <span class="number">2017</span></span><br><span class="line">A结束了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">23</span> CST <span class="number">2017</span></span><br><span class="line">A运行了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">23</span> CST <span class="number">2017</span></span><br><span class="line">A结束了！时间为:Tue May <span class="number">16</span> <span class="number">08</span>:<span class="number">39</span>:<span class="number">28</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>任务被延时但还是一个一个顺序执行</p>
<p><strong>4. TimerTask类的cancel()方法</strong></p>
<p>TimerTask类中的cancel()方法的作用是将自身从任务队列中清除<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTaskA</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"A运行了！时间为:"</span> + <span class="keyword">new</span> Date());</span><br><span class="line">            <span class="keyword">this</span>.cancel();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTaskB</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"B运行了！时间为:"</span> + <span class="keyword">new</span> Date());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTaskA taskA = <span class="keyword">new</span> MyTaskA();</span><br><span class="line">            MyTaskB taskB = <span class="keyword">new</span> MyTaskB();</span><br><span class="line">            SimpleDateFormat sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString = <span class="string">"2017-5-18 8:09:00"</span>;</span><br><span class="line">            Timer timer = <span class="keyword">new</span> Timer();</span><br><span class="line">            Date dateRef = sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span> + dateRef.toString() + <span class="string">"当前时间:"</span> + <span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(taskA, dateRef, <span class="number">4000</span>);</span><br><span class="line">            timer.schedule(taskB, dateRef, <span class="number">4000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">09</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">47</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line">A运行了！时间为:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">47</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line">B运行了！时间为:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">47</span>:<span class="number">24</span> CST <span class="number">2017</span></span><br><span class="line">B运行了！时间为:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">47</span>:<span class="number">28</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>TimerTask类的cancel()方法是将自身从任务队列中被移除，其他任务不受影响。</p>
<p><strong>5. Timer类的cancel()方法</strong><br>和TimerTask类中的cancel()方法清除自身不同，Timer类中的cancel()方法的作用是将任务队列中的全部任务清空。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer timer=<span class="keyword">new</span> Timer();</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTaskA</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"A运行了！时间为:"</span> + <span class="keyword">new</span> Date());</span><br><span class="line">            timer.cancel();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTaskB</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"B运行了！时间为:"</span> + <span class="keyword">new</span> Date());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            MyTaskA taskA = <span class="keyword">new</span> MyTaskA();</span><br><span class="line">            MyTaskB taskB = <span class="keyword">new</span> MyTaskB();</span><br><span class="line">            SimpleDateFormat sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">            String dateString = <span class="string">"2017-5-18 8:09:00"</span>;</span><br><span class="line">            Date dateRef = sdf.parse(dateString);</span><br><span class="line">            System.out.println(<span class="string">"字符串时间:"</span> + dateRef.toString() + <span class="string">"当前时间:"</span> + <span class="keyword">new</span> Date().toString());</span><br><span class="line">            timer.schedule(taskA, dateRef, <span class="number">4000</span>);</span><br><span class="line">            timer.schedule(taskB, dateRef, <span class="number">4000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序的运行结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">字符串时间:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">09</span>:<span class="number">00</span> CST <span class="number">2017</span>当前时间:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">56</span>:<span class="number">39</span> CST <span class="number">2017</span></span><br><span class="line">A运行了！时间为:Thu May <span class="number">18</span> <span class="number">08</span>:<span class="number">56</span>:<span class="number">39</span> CST <span class="number">2017</span></span><br></pre></td></tr></table></figure></p>
<p>全部任务都被清除，并且进程被销毁，按钮由红色变成灰色。</p>
<p><strong>6. Timer的cancel()方法注意事项</strong><br>Timer类中的cancel()方法有时并一定会停止执行计划任务，而是正常执行。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> wuyoushan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/3/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Run</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> i=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTask</span> <span class="keyword">extends</span> <span class="title">TimerTask</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"正常执行了"</span> +i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                i++;</span><br><span class="line">                Timer timer = <span class="keyword">new</span> Timer();</span><br><span class="line">                MyTask task = <span class="keyword">new</span> MyTask();</span><br><span class="line">                SimpleDateFormat sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">                String dateString = <span class="string">"2017-5-18 8:09:00"</span>;</span><br><span class="line">                Date dateRef = sdf.parse(dateString);</span><br><span class="line">                timer.schedule(task, dateRef);</span><br><span class="line">                timer.cancel();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (ParseException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>程序运行后的部分结果为:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">正常执行了<span class="number">2</span></span><br><span class="line">正常执行了<span class="number">163</span></span><br><span class="line">正常执行了<span class="number">347</span></span><br><span class="line">正常执行了<span class="number">542</span></span><br><span class="line">正常执行了<span class="number">622</span></span><br><span class="line">正常执行了<span class="number">739</span></span><br><span class="line">正常执行了<span class="number">751</span></span><br><span class="line">正常执行了<span class="number">852</span></span><br><span class="line">正常执行了<span class="number">1233</span></span><br></pre></td></tr></table></figure></p>
<p>这是因为Timer类中的cancel()方法有时并没有争抢到queue锁，所以TimerTask类中的任务继续正常执行。</p>
<blockquote>
<p>摘选自 java多线程核心编程技术-5.1.2</p>
</blockquote>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
  </section>

  
  <nav class="pagination">
    <span class="page-number current">1</span><a class="page-number" href="/learning/page/2/">2</a><span class="space">&hellip;</span><a class="page-number" href="/learning/page/7/">7</a><a class="extend next" rel="next" href="/learning/page/2/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/learning/images/avatar.gif" alt="wuyoushan">
          <p class="site-author-name" itemprop="name">wuyoushan</p>
           
              <p class="site-description motion-element" itemprop="description">W3C菜鸟</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/learning/archives/">
                <span class="site-state-item-count">61</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/learning/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/learning/tags/index.html">
                <span class="site-state-item-count">8</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://git.oschina.net/wuyoushan" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="翟永超的博客" target="_blank">翟永超的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://itmuch.com/" title="周立的博客" target="_blank">周立的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.bysocket.com/" title="泥瓦匠的博客" target="_blank">泥瓦匠的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.720ui.com/" title="梁桂钊的博客" target="_blank">梁桂钊的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://kailing.pub/" title="KL博客" target="_blank">KL博客</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wuyoushan</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/learning/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/learning/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/learning/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/learning/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/learning/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/learning/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/learning/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/learning/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/learning/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/learning/js/src/schemes/pisces.js?v=5.1.1"></script>



  
    <script type="text/javascript" src="/learning/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/learning/js/src/post-details.js?v=5.1.1"></script>

  

  


  <script type="text/javascript" src="/learning/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/learning/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
